var $ = window.$;
var jade = require('jade');
var animate = require('../../util/animate');
var event = require('../../core/event');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var config = require('../../core/config');
var path = require('path');
var notify = require('../notify/ui');
var toolbar = require('../toggle/ui');
var io = require('../io/ui');

var _inited = false;

/**
 * 引导
 */

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		this.total = 3;
		event.bind(event.events.dialog.create, 'guide_create', this);
		_inited = true;
	},

	onEvent: function(e, param){
		if(e == event.events.dialog.create){
			this.show(param);
			return true;
		}else if(e == event.events.key.up){
			if(param.key == 27) {
				this.hide();
				return event.result.stopAll;
			}
		}else if(e == event.events.global.drop){
			if(param.target.id == 'create_music'){
				if(!param || !param.dataTransfer.files.length){
					return;
				}
				this.file = param.dataTransfer.files[0].path;
				var ext = path.extname(this.file);
				if(ext == '.mp3' || ext == '.wav' || ext == '.ogg'){
					this.parent.find("#create_music").addClass('ok');
					return event.result.stopAll;
				}
			}
		}
	},

	/**
	 * sound: file, bpm, offset, beat
	 * @param sound
	 */
	addSoundNote: function(sound) {
		var note = require('../note/manager');
		var grid = require('../grid/manager');
		var chart = note.getNote('main');
		//1. 加入sample库
		event.trigger(event.events.sample.add, {file: sound.file});
		//2. 加入note
		//注意, 这一段代码涉及note属性控制, 本来应该封装在note manager里
		//但仅有这一处特化的场合使用, 故留在这里
		var _note = {
			sound: path.basename(sound.file),
			type: 1,
            isBgm : true
		};
		if(sound.offset){
			_note.offset = sound.offset; //这个传入时已经确保在-200 ~ 200范围
		}
		if(sound.beat){
			_note.beat = sound.beat;
		}else{
			_note.beat = [0, 0, 4];
		}

		_note.type = 1;
		var id = grid.addNote(_note);
		//3. 改变基础bpm
		var timing = require('../timing/manager');
		timing.change({beat:[0,0,4]}, {bpm: sound.bpm});

		if(chart.meta.mode < 3){
			var col = chart.meta.mode_ext.column;  //前一步设定的值, 不存在就报错
			_note.column = col;

			var toggle = [0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0];
			for(var i=0;i<col;i++){
				toggle[i] = 1;
			}
			toggle[col] = 2;
			util.setJsonChainValue(chart, 'extra.toggle', toggle);
		}else if(chart.meta.mode == 3){
			_note.x = 540;
		}else if(chart.meta.mode == 4){
			_note.column = 0;
			util.setJsonChainValue(chart, 'extra.toggle', [2]);
		}else if(chart.meta.mode == 5){
			_note.column = 6;
		}

		//4. 触发刷新
		event.trigger(event.events.grid.sync, {isMCE: true});
		//event.trigger(event.events.grid.focus, {id: id});
		event.trigger(event.events.note.change);
		grid.loadSamples();
        //5.切换工具
        toolbar.updateTool(3);
	},

	changePage: function(delta){
		this.curr += delta;
		var tmpl = jade.compileFile('./tmpl/guide/create/'+this.curr+'.jade');
		this.parent.find('.title').html("Step "+(this.curr + 1));
		this.parent.find('.body').html(tmpl({config: config}));
		if(this.curr == this.total - 1){
			this.parent.find('.g_bt span').eq(1).html("Close");
            this.parent.find('span[data-type="cancel"]').hide();
		}
	},

	show: function(param){
		this.curr = 0;
		if(param && param.sound){
			//从timing跳回来的话会带上这个字段
			this.curr = 2;
		}
		var tmpl = jade.compileFile('./tmpl/guide/intro.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_intro');
		this.parent.css({
			height: '250px',
			marginTop: '-125px'
		});

		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'next'){
				if(self.curr == 1){
					if(!self.file){
						notify.addNotify({
							msg: config.i18n('err07')
						});
						return;
					}
					self.hide();
					event.trigger(event.events.sample.timing, {file: self.file, back: 'create'});
				}else if(self.curr == 2){
					self.hide();
				}else{
					self.changePage(1);
				}
			}else if(type == 'cancel'){
                self.hide();
            }else if(type == 'sound'){
				io.getSoundPath().then(function (file) {
					if(file){
						self.file = file;
						var ext = path.extname(file);
						if(ext == '.mp3' || ext == '.wav' || ext == '.ogg'){
							self.parent.find("#create_music").addClass('ok');
						}
					}
				});
			}
		});

		this.parent.show();
		uiUtil.dialogInc();
		animate.normalScaleIn(this.parent).then(function(){
			self.changePage(0);
			if(param && param.sound){
				self.addSoundNote(param.sound);
			}
		});

		event.bind(event.events.key.up, 'guide_create', this);
		event.bind(event.events.global.drop, 'guide_create', this);
		event.lock('key', 'guide_create');
		event.trigger(event.events.global.blur);

	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.normalScaleOut(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbindByKey('guide_create');
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;